package com.sun.springmvc.frmework;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class Handler {
    private Object object;
    private Method method;
    private Pattern pattern;
    private Map<String, Integer> indexMap;
    private List<String> securityList = new ArrayList<>();

    public Handler(Object object, Method method, Pattern pattern) {
        this.object = object;
        this.method = method;
        this.pattern = pattern;
        indexMap = new HashMap<>();
    }

    public Object getObject() {
        return object;
    }

    public void setObject(Object object) {
        this.object = object;
    }

    public Method getMethod() {
        return method;
    }

    public void setMethod(Method method) {
        this.method = method;
    }

    public Pattern getPattern() {
        return pattern;
    }

    public void setPattern(Pattern pattern) {
        this.pattern = pattern;
    }

    public Map<String, Integer> getIndexMap() {
        return indexMap;
    }

    public void setIndexMap(Map<String, Integer> indexMap) {
        this.indexMap = indexMap;
    }

    public List<String> getSecurityList() {
        return securityList;
    }

    public void setSecurityList(List<String> securityList) {
        this.securityList = securityList;
    }


    public void invoke(HttpServletResponse resp, Object[] objects, String username) {

        if (securityList.size() > 0 && securityList.contains(username) && !StringUtils.isEmpty(username)) {
            try {
                method.invoke(object, objects);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } else {
            try {
                resp.setCharacterEncoding("UTF-8");
                resp.setHeader("Content-type", "text/html;charset=UTF-8");
                resp.getWriter().write(username + " 没有访问的权限");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
